package com.haiyi.software.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.R.integer;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.haiyi.software.app.MainApplication;
import com.haiyi.software.entity.BeanLoginResultBody;
import com.haiyi.software.entity.EntityChat;
import com.haiyi.software.entity.EntityInformationCount;
import com.haiyi.software.tools.MyDBHelper;
import com.haiyi.software.tools.MyTools;

public class ChatDAO {

	private MyDBHelper dbHelper;

	private static ChatDAO ChatDAOInstance = null;

	public static ChatDAO getInstence() {

		if (ChatDAOInstance == null) {
			ChatDAOInstance = new ChatDAO();
		}

		return ChatDAOInstance;
	}

	public void distoryDB() {

		this.dbHelper = null;
		ChatDAOInstance = null;
	}

	private ChatDAO() {
		String dbName = "db_"
				+ MainApplication.getInstance().getMineUserInfo().getUid()
				+ ".db";
		dbHelper = new MyDBHelper(dbName);

	}

	public void Add(EntityChat chat) {

		SQLiteDatabase db = dbHelper.getWritableDatabase();

		db.execSQL(
				"INSERT INTO tb_message(hi_id,name,body,times,state,read_state,download,siID,uhead)VALUES(?,?,?,?,?,?,?,?,?)",
				new Object[] { chat.getHi_id(), chat.getName(), chat.getBody(),
						chat.getTimes(), chat.getState(), chat.getRead_state(),
						chat.getDownload(), chat.getSiID(), chat.getUhead() });

		// dbHelper.close();

	}

	public void Delete(int id) {

		SQLiteDatabase db = dbHelper.getWritableDatabase();

		db.execSQL("DELETE FROM tb_message WHERE id=?", new Object[] { id });

		// dbHelper.close();

	}

	public void Update(EntityChat chat) {

		SQLiteDatabase db = dbHelper.getWritableDatabase();

		db.execSQL(
				"UPDATE tb_message SET hi_id=?,name=?,body=?,times=?,state=?,read_state=?,download=?,siID=?,uhead=? WHERE id=?",
				new Object[] { chat.getHi_id(), chat.getName(), chat.getBody(),
						chat.getTimes(), chat.getState(), chat.getRead_state(),
						chat.getDownload(), chat.getSiID(), chat.getId(),
						chat.getUhead() });

		// dbHelper.close();

	}

	public List<EntityChat> GetAll() {

		SQLiteDatabase db = dbHelper.getWritableDatabase();

		List<EntityChat> chats = new ArrayList<EntityChat>();

		Cursor cursor = db.rawQuery("SELECT * FROM tb_message ORDER BY id ASC",
				null);

		while (cursor.moveToNext()) {

			int id = cursor.getInt(cursor.getColumnIndex("id"));
			String hi_id = cursor.getString(cursor.getColumnIndex("hi_id"));
			String name = cursor.getString(cursor.getColumnIndex("name"));
			String body = cursor.getString(cursor.getColumnIndex("body"));
			String times = cursor.getString(cursor.getColumnIndex("times"));
			String state = cursor.getString(cursor.getColumnIndex("state"));
			String read_state = cursor.getString(cursor
					.getColumnIndex("read_state"));
			String download = cursor.getString(cursor
					.getColumnIndex("download"));
			String siID = cursor.getString(cursor.getColumnIndex("siID"));
			String uhead = cursor.getString(cursor.getColumnIndex("uhead"));

			EntityChat chat = new EntityChat();

			chat.setId(id);
			chat.setBody(body);
			chat.setDownload(download);
			chat.setHi_id(hi_id);
			chat.setName(name);
			chat.setRead_state(read_state);
			chat.setSiID(siID);
			chat.setState(state);
			chat.setTimes(times);
			chat.setUhead(uhead);
			chats.add(chat);
		}

		// dbHelper.close();

		return chats;
	}

	/*
	 * 返回未读消息个数及相关信息
	 */
	public List<Map<String, Object>> getInformationCount() {

		SQLiteDatabase db = dbHelper.getWritableDatabase();

		List<Map<String, Object>> inforCnt = new ArrayList<Map<String, Object>>();

		Cursor cursor = db
				.rawQuery(
						"SELECT hi_id,name,uhead,sum(cnt) AS cnt, times , body from (SELECT hi_id,name,uhead,COUNT(*) AS cnt, times , body FROM tb_message  WHERE   read_state=0 GROUP BY hi_id   UNION SELECT hi_id,name,uhead,0 cnt, times , body FROM tb_message WHERE  read_state=1 GROUP BY hi_id  ) GROUP BY hi_id ORDER BY times DESC",
						null);
		while (cursor.moveToNext()) {
			// "SELECT hi_id,name,uhead,COUNT(*) AS cnt, times , body FROM tb_message WHERE read_state='0' GROUP BY hi_id",

			String hi_id = cursor.getString(cursor.getColumnIndex("hi_id"));
			String name = cursor.getString(cursor.getColumnIndex("name"));
			String times = cursor.getString(cursor.getColumnIndex("times"));
			String uhead = cursor.getString(cursor.getColumnIndex("uhead"));
			String cnt = cursor.getString(cursor.getColumnIndex("cnt"));
			String body = cursor.getString(cursor.getColumnIndex("body"));
			Map<String, Object> ef = new HashMap<String, Object>();

			ef.put("hi_id", hi_id);
			ef.put("name", name);
			ef.put("times", times);
			ef.put("uhead", uhead);
			ef.put("cnt", cnt);
			ef.put("body", body);
			inforCnt.add(ef);

		}
		// dbHelper.close();
		return inforCnt;
	}

	/**
	 * 返回我与指定人的对话信息
	 * 
	 * @param uid
	 *            对方的ID
	 * @param limit
	 *            显示多少条，如果全部显示则 -1
	 * @return List<EntityChat>
	 */
	public List<EntityChat> getMessageList(String uid, String limit) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();

		List<EntityChat> chats = new ArrayList<EntityChat>();

		Cursor cursor = null;

		if (limit == "-1") {
			cursor = db.rawQuery(
					"SELECT * FROM tb_message WHERE hi_id=? ORDER BY id DESC",
					new String[] { uid });
		} else {
			cursor = db
					.rawQuery(
							"SELECT * FROM tb_message WHERE hi_id=? ORDER BY id DESC LIMIT 0,?",
							new String[] { uid, limit });

		}

		while (cursor.moveToNext()) {

			int id = cursor.getInt(cursor.getColumnIndex("id"));
			String hi_id = cursor.getString(cursor.getColumnIndex("hi_id"));
			String name = cursor.getString(cursor.getColumnIndex("name"));
			String body = cursor.getString(cursor.getColumnIndex("body"));
			String times = cursor.getString(cursor.getColumnIndex("times"));
			String state = cursor.getString(cursor.getColumnIndex("state"));
			String read_state = cursor.getString(cursor
					.getColumnIndex("read_state"));
			String download = cursor.getString(cursor
					.getColumnIndex("download"));
			String siID = cursor.getString(cursor.getColumnIndex("siID"));
			String uhead = cursor.getString(cursor.getColumnIndex("uhead"));

			EntityChat chat = new EntityChat();

			chat.setId(id);
			chat.setBody(body);
			chat.setDownload(download);
			chat.setHi_id(hi_id);
			chat.setName(name);
			chat.setRead_state(read_state);
			chat.setSiID(siID);
			chat.setState(state);
			chat.setTimes(times);
			chat.setUhead(uhead);
			chats.add(chat);
		}

		// dbHelper.close();

		return chats;
	}

	/**
	 * 把指定人的消息设置为已读
	 * 
	 * @param uid
	 *            指定人的UID
	 */
	public void changeMessageStateToRead(String uid) {

		SQLiteDatabase db = dbHelper.getWritableDatabase();

		db.execSQL("UPDATE tb_message SET read_state=1 WHERE hi_id=?",
				new Object[] { uid });

		// dbHelper.close();
	}

	/**
	 * 根据消息ID，设置为已读
	 * 
	 * @param sid
	 *            消息的唯一sid
	 */
	public void changeMessageStateToReadBySID(String sid) {

		SQLiteDatabase db = dbHelper.getWritableDatabase();

		db.execSQL("UPDATE tb_message SET read_state=1 WHERE siID=?",
				new Object[] { sid });

		// dbHelper.close();
	}

	/**
	 * 更新消息体（BODY）
	 * 
	 * @param sid
	 *            消息ID
	 * @param msgNew
	 *            新的整个消息
	 */
	public void changeNewMessageBody(String sid, String msgNew) {

		SQLiteDatabase db = dbHelper.getWritableDatabase();

		db.execSQL("UPDATE tb_message SET body=? WHERE siID=?", new Object[] {
				msgNew, sid });

		Log.i("数据库操作", sid + "::::更新成功:::::" + msgNew);

		// dbHelper.close();
	}

	/**
	 * 获取未读消息的个数
	 * 
	 * @return
	 */
	public Integer getUnreadCount() {

		int cnt = 0;

		SQLiteDatabase db = dbHelper.getWritableDatabase();

		Cursor cursor = db.rawQuery(
				"SELECT COUNT(*) AS CNT FROM tb_message WHERE read_state=0",
				null);
		if (cursor.moveToNext()) {

			cnt = cursor.getInt(cursor.getColumnIndex("CNT"));
		}

		return cnt;
	}
}
